package work_pattern.routing;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import work_pattern.Constant;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RoutingProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = Constant.createChannel();
        /**
         * exchange: 交换机名称
         * BuiltinExchangeType type: 交换机类型
         *      DIRECT("direct") 定向routing, FANOUT("fanout") 广播, TOPIC("topic") 通配符, HEADERS("headers")参数匹配
         * durable: 持久化
         * autoDelete: 自动删除
         * internal: 是否内部使用，若为true, 客户端无法直接发送消息到该交换机, 只能通过交换机路由到交换机
         * arguments: 参数
         */
        channel.exchangeDeclare(Constant.ROUTING_EXCHANGE, BuiltinExchangeType.DIRECT, true, false, false, null);
        channel.queueDeclare(Constant.ROUTING_QUEUE_1, true, false, false, null);
        channel.queueDeclare(Constant.ROUTING_QUEUE_2, true, false, false, null);
        // 绑定交换机和队列
        // 交换机类型为 fanout, routingKey 设置为 "", 表示每个消费者都可以收到全部信息
        channel.queueBind(Constant.ROUTING_QUEUE_1, Constant.ROUTING_EXCHANGE, Constant.ROUTING_KEY_1);
        channel.queueBind(Constant.ROUTING_QUEUE_2, Constant.ROUTING_EXCHANGE, Constant.ROUTING_KEY_2);
        channel.queueBind(Constant.ROUTING_QUEUE_2, Constant.ROUTING_EXCHANGE, Constant.ROUTING_KEY_3);
        channel.queueBind(Constant.ROUTING_QUEUE_1, Constant.ROUTING_EXCHANGE, Constant.ROUTING_KEY_3);
        for (int i = 0; i < 10; i++) {
            channel.basicPublish(Constant.ROUTING_EXCHANGE, Constant.ROUTING_KEY_1, null, new String("KEY1 hello " + i).getBytes());
            channel.basicPublish(Constant.ROUTING_EXCHANGE, Constant.ROUTING_KEY_2, null, new String("KEY2 hello " + i).getBytes());
            channel.basicPublish(Constant.ROUTING_EXCHANGE, Constant.ROUTING_KEY_3, null, new String("KEY3 hello " + i).getBytes());
        }
        System.out.println("消息发送成功");
    }
}
